<template>
  <div :class="['search-box', active ? 'active' : '']">
    <i class="icon el-icon-search search" @click="search"></i>
    <input
      ref="input"
      type="text"
      v-model="value"
      @keyup.enter="search"
      :placeholder="placeholder">
    <i class="icon el-icon-close clear" v-show="active" @click="clear"></i>
  </div>
</template>
<script>
export default {
  props: {
    placeholder: String,
    keyword: String,
  },
  data() {
    return {
      value: null,
      active: false,
    };
  },
  created() {
    this.value = this.keyword;
    this.active = !!this.value;
  },
  watch: {
    active(value) {
      if (value) {
        this.$emit('active');
      } else {
        this.$emit('deactive')
      }
    }
  },
  methods: {
    search() {
      if (!this.active) {
        this.active = true;
        this.$refs.input.focus();
        return false;
      }
      if (this.value && this.value.trim()) {
        this.$emit('search', this.value.trim());
      }
    },
    clear() {
      if (this.active) {
        this.$emit('clear');
        this.active = false;
      } else {
        this.active = false;
      }
    }
  },
}
</script>
<style scoped lang="scss">
  .search-box {
    position: relative;
    vertical-align: middle;
    input {
      opacity: 0;
      background: #1f2d3d;
      border-radius: 4px;
      border: none;
      width: 20px;
      transition: width .3s ease-in-out;
    }
    .icon {
      position: absolute;
      vertical-align: middle;
      color: #fff;
      font-size: 20px;
      z-index: 1;
      &:hover {
        cursor: pointer;
        color: #bac8dc;
      }
      &.clear {
        top: 8px;
        right: 10px;
        font-size: 16px;
      }
    }
    &.active {
      line-height: 30px;
      input {
        opacity: 1;
        padding: 0 30px;
        width: 240px;
        line-height: 30px;
      }
      .icon {
        color: #8492a6;
        &.search {
          left: 10px;
          top: 6px;
        }
      }
    }
  }
</style>
